<template>
	<view>
		<view class="goeasy-recorder">
			<view @touchstart="startRecord" @touchend="stopRecord" class="record-msg-box">
				{{recording ? '松开发送' : '按下录音'}}
			</view>
			<image v-if="recording" class="record-icon" src="/static/images/recording-loading.gif" />
		</view>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	export default {
		name: "goEasyRecorder",
		props: {
			addGlobalClass: {
				type: Boolean,
				default: true
			},
		},
		data() {
			return {
				recording: false,
				stopSignaled: false,
				clickLongPress: false,
			};
		},
		mounted() {
			var self = this;
			recorderManager.onStart(function() {
				self.recording = true;
				self.clickLongPress = false
				if (self.stopSignaled) {
					self.stopSignaled = false
					recorderManager.stop();
				}
			});
			recorderManager.onStop(function(res) {
				self.recording = false;
				if (res.duration < 1000) {
					uni.showToast({
						icon: 'none',
						title: '录音时间太短',
						duration: 500
					});
					return;
				} else {
					self.triggerEvent('onStop', res);
				}
			});
			recorderManager.onError(function() {
				self.recording = false;
			});
		},
		methods: {
			startRecord: function() {
				// console.log('start');
				this.clickLongPress = true;
				recorderManager.start();
			},
			stopRecord: function() {
				console.log('end');

				if (!this.recording && this.clickLongPress) {
					console.log('in1', this.clickLongPress);
					this.stopSignaled = true;
					this.clickLongPress = false;
				} else {
					this.recording = false;
					recorderManager.stop();
				}
			}
		},
	}
</script>

<style scoped>
	.goeasy-recorder {
		height: 50rpx;
		background-color: #ffffff;
		/* flex: 1; */
		display: flex;
	}


	.record-msg-box {
		flex: 1;
		height: 50rpx;
		/* padding-left: 20rpx; */
		/* padding: 12rpx; */
		border-radius: 12rpx;
		box-sizing: border-box;
		line-height: 50rpx;
		text-align: center;
		color: #FFFFFF;
		background: #ccc;
		margin-right: 20rpx;
	}

	.record-icon {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 158rpx;
		margin: auto;
		width: 316rpx;
		height: 308rpx;
	}
</style>